package com.emily.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.TMenu;
import com.emily.test.model.TResource;
import com.emily.test.model.TRole;
import com.emily.test.service.RoleService;
import com.emily.test.service.TMenuService;
import com.emily.test.service.TRoleMenuService;
import com.emily.test.utils.ConstentUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(value = "TRoleMenuController")
@Api(value = "TRoleMenuApi", description = "TRoleMenu接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class TRoleMenuController {
    private Logger logger = LoggerFactory.getLogger(TResourceController.class);

    @Autowired
    private TRoleMenuService tRoleMenuService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private TMenuService tMenuService;

    /**
     * 根据角色信息查询角色与菜单的关联信息列表
     * @param jsonObject 包含角色信息查询条件
     * @return  符合查询条件的角色与菜单的相关信息列表
     */
    @ApiOperation(value="根据角色信息查询角色与菜单的关联信息列表", notes="TRoleMenu")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色ID"),
            @ApiImplicitParam(name = "rName", value = "角色名称"),
            @ApiImplicitParam(name = "rCode", value = "角色code"),
            @ApiImplicitParam(name = "state", value = "角色状态"),
            @ApiImplicitParam(name = "serial", value = "显示顺序"),
            @ApiImplicitParam(name = "description", value = "备注"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间")
    })
    @PostMapping("getRoleMenuInfoListByRoleCondition")
    public ResponseResult getRoleMenuInfoListByRoleCondition(@RequestBody JSONObject jsonObject){

        List<Map<String,Object>> all_list = new ArrayList<Map<String,Object>>();
        Integer id=jsonObject.getInteger("id");
        String rName=jsonObject.getString("rName");
        String rCode=jsonObject.getString("rCode");
        Integer state=jsonObject.getInteger("state");
        Integer serial=jsonObject.getInteger("serial");
        String description=jsonObject.getString("description");
        String updateTime=jsonObject.getString("updateTime");
        TRole tRole=new TRole();
        tRole.setId(id);
        tRole.setrName(rName);
        tRole.setrCode(rCode);
        tRole.setState(state);
        tRole.setSerial(serial);
        tRole.setDescription(description);
        tRole.setUpdateTime(updateTime);
        try {
            //根据条件查询角色信息列表
            List<TRole> roleList=roleService.selectRoleByCondition(tRole);
            if(!ConstentUtil.isEmpty(roleList)){
                String stringBuffer="";
                for(TRole tRole1 : roleList){
                    stringBuffer +=tRole1.getId()+",";
                }
                stringBuffer= stringBuffer.substring(0,stringBuffer.length()-1).trim();
                List li= ConstentUtil.strToList(stringBuffer);

                List<Map<String,Object>> tResourceList= tRoleMenuService.getMenuListByRoleIds(li);
                if(!ConstentUtil.isEmpty(tResourceList)){

                    String[] strs = stringBuffer.split(",");
                    for (int j = 0; j < strs.length; j++) {
                        HashMap<String, Object> hm = new HashMap<>();
                        List list1 = new ArrayList();
                        for (int i = 0; i < tResourceList.size(); i++) {
                            if(strs[j].equals(tResourceList.get(i).get("roleId").toString())) {
                                hm.put("roleId", strs[j]);
                                hm.put("rName", tResourceList.get(i).get("rName").toString());
                                list1.add(tResourceList.get(i));
                                hm.put("data",list1);
                            }
                        }
                        if(hm.size()!=0){
                            all_list.add(hm);
                        }
                    }
                }
            }
            logger.info("查询角色与资源信息成功:{}",all_list);
            return ResponseResult.success(all_list);
        } catch (Exception e) {
            logger.error("查询角色与资源信息异常:",e);
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }

    /**
     * 根据角色ID查询对应的菜单信息列表
     *
     * @param jsonObject 角色id集合，其中参数key为roleIds，值形式为:"1,2,3,4"
     * @return
     */
    @ApiOperation(value = "根据角色ID查询对应的菜单信息列表", notes = "TRoleResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleIds", value = "角色ID集合", required = true)
    })
    @PostMapping(value = "selectTMenuInfoByRoleIds")
    public ResponseResult selectTMenuInfoByRoleIds(@RequestBody JSONObject jsonObject) {
        String roleIds = jsonObject.getString("roleIds");
        try {
            List<Map<String,Object>> tResourceList= tRoleMenuService.getMenuListByRoleIds(ConstentUtil.strToList(roleIds));
            String[] strs = roleIds.split(",");
            List alllist = new ArrayList();
            for (int j = 0; j < strs.length; j++) {
                HashMap<String, Object> hm = new HashMap<>();
                List list1 = new ArrayList();
                for (int i = 0; i < tResourceList.size(); i++) {
                    if(strs[j].equals(tResourceList.get(i).get("roleId").toString())) {
                        hm.put("roleId", strs[j]);
                        hm.put("rName", tResourceList.get(i).get("rName").toString());
                        list1.add(tResourceList.get(i));
                        hm.put("data",list1);
                    }
                }
                if(hm.size()!=0){
                    alllist.add(hm);
                }
            }
            logger.info("查询t_resource成功，list={}",alllist);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS,alllist);
        } catch (Exception e) {
            logger.error("查询t__resource异常:{}", e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 插入角色与菜单关联表信息
     * @param jsonObject 包含角色ID（roleId）与菜单（menuIds）关联表集合 ，其中roleId格式为Integer，menuIds格式为List集合
     * @return
     */
    @ApiOperation(value="插入角色与菜单关联表信息", notes="RCompanyRole")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "公司ID", required = true),
            @ApiImplicitParam(name = "menuIds", value = "菜单ID", required = true)
    })
    @PostMapping(value = "insertRoleMenusInfo")
    public ResponseResult insertRoleMenusInfo(@RequestBody JSONObject jsonObject){
        Map<String,Object> map=jsonObject.getInnerMap();
        try {
            int num=tRoleMenuService.insertRoleMenusInfo(map);
            if(num==0){
                logger.error("未插入任何角色与菜单关联表的数据,插入数据条数:{}",num);
                return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
            }
            logger.info("角色与菜单关联表信息"+ReturnValueConstants.ADD_SUCCESS+"增加条数：{}",num);
            return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS,num);
        } catch (Exception e) {
            logger.error("插入角色与菜单关联表信息异常{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }

    /**
     *根据角色ID删除对应的菜单ID
     * @param jsonObject
     * @return
     */
    @ApiOperation(value="根据角色ID删除对应的菜单ID", notes="TRoleMenu")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleIds", value = "角色ID", required = true)
    })
    @PostMapping(value = "deleteTRoleMenuByRoleIds")
    public ResponseResult deleteTRoleMenuByRoleIds(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("roleIds").replaceAll("\\[","").replaceAll("]","");

        if(ConstentUtil.isEmpty(ids)){
            return ResponseResult.fail("角色"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        //查看删除的是否含有超管，如果有则不允许删除
        TRole tRole=new TRole();
        tRole.setrCode("SUPERADMIN");
        List<TRole> tRoleList= roleService.selectRoleByCondition(tRole);
        if(!ConstentUtil.isEmpty(tRoleList)){
            tRole=tRoleList.get(0);
        }
        Integer superAdminRoleId=tRole.getId();
        String[] idStr=ids.split(",");
        for(int i=0;i<idStr.length;i++){
            Integer roleId=Integer.valueOf(idStr[i].toString().trim());
            if(superAdminRoleId.equals(roleId)){
                return  ResponseResult.fail("超管不允许删除，请重新选择");
            }
        }
        List<Integer> roleIdList=new ArrayList<Integer>();
        for( int i=0;i<idStr.length;i++){
             Integer roleId=Integer.valueOf(idStr[i].toString().trim());
             roleIdList.add(roleId);
        }
        try {
            int num= tRoleMenuService.deleteByRoleIdList(roleIdList);
            logger.info("删除t_role_menu成功，删除数量={}",num);
            return ResponseResult.success(ReturnValueConstants.DELATE_SUCCESS,num);
        } catch (Exception e) {
            logger.error("删除t_role_menu异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.DELATE_FAILURE);
        }
    }

    /**
     * 根据角色ID获取角色信息以及所有的菜单信息集合，其中公司已经有的菜单信息添加selected=1属性，没有的则为selected=0.
     * @param jsonObject
     * @return
     */
    @ApiOperation(value="根据角色ID获取角色信息以及所有的菜单信息集合，其中公司已经有的菜单信息添加selected=1属性，" +
            "没有的则为selected=0.", notes="TRoleMenu")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色ID", required = true)
    })
    @PostMapping(value = "getRoleAndAllMenuInfoByRoleId")
    public ResponseResult getRoleAndAllMenuInfoByRoleId(@RequestBody JSONObject jsonObject){
        try {
            //角色ID
            Integer roleId=jsonObject.getInteger("id");

            //根据角色ID获取角色信息
            TRole tRole=roleService.selectRoleById(roleId);

            //获取角色已经存在的菜单信息列表
            List list=new ArrayList();
            list.add(roleId);
            List<Map<String,Object>> tMenuLists= tRoleMenuService.getMenuListByRoleIds(list);

            //获取所有启用的菜单信息
            TMenu tMenu=new TMenu();
            tMenu.setState(1);
            List<TMenu> tMenuList=tMenuService.getMenuInfoListByCondition(tMenu);

            Map<String,Object> returnMapList=new HashMap<String,Object>();
            //将角色信息放入map
            returnMapList.put("id",tRole.getId());
            returnMapList.put("rName",tRole.getrName());
            returnMapList.put("rCode",tRole.getrCode());
            returnMapList.put("roleState",tRole.getState());
            returnMapList.put("roleSerial",tRole.getSerial());
            returnMapList.put("roleDescription",tRole.getDescription());
            returnMapList.put("roleUpdateTime",tRole.getUpdateTime());

            //将资源信息放入集合
            List<Map<String,Object>> inputList=new ArrayList<Map<String,Object>>();
            if(!ConstentUtil.isEmpty(tMenuList)){
                for(TMenu tMenu1 : tMenuList){

                    int allResourceId=tMenu1.getId();

                    Map<String,Object> resourceMap=new HashMap<>();
                    resourceMap.put("menuId",tMenu1.getId());
                    resourceMap.put("menuName",tMenu1.getMenuName());
                    resourceMap.put("resourceId",tMenu1.getResourceId());
                    resourceMap.put("pageurl",tMenu1.getPageurl());
                    resourceMap.put("menuState",tMenu1.getState());
                    resourceMap.put("resourceName",tMenu1.getResourceName());
                    resourceMap.put("menuUpdateTime",tMenu1.getUpdateTime());

                    if(!ConstentUtil.isEmpty(tMenuLists)){
                        for(Map<String,Object> rMap : tMenuLists){
                            int partResourceId=(int) rMap.get("id");
                            //添加角色含有的菜单信息到map，并且为其添加属性selected ： true
                            if(allResourceId==partResourceId){
                                resourceMap.put("selected","1");
                                break;
                            }else{
                                resourceMap.put("selected","0");
                            }
                        }
                    }else{
                        resourceMap.put("selected","0");
                    }
                    inputList.add(resourceMap);
                }
            }
            returnMapList.put("menuList",inputList);
            logger.info("查询角色菜单信息成功:{}",returnMapList);
            return ResponseResult.success(returnMapList);
        } catch (Exception e) {
            logger.error("查询角色菜单信息异常",e);
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }

    /**
     * 更新角色与菜单关系信息表
     * @param jsonObject 包含角色（roleId）与资源（menuIds）关联表集合 ，其中roleId格式为Integer，menuIds格式为List集合
     * @return
     */
    @ApiOperation(value="更新角色与菜单关系信息表", notes="更新角色与菜单关系信息表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true),
            @ApiImplicitParam(name = "menuIds", value = "菜单ID")
    })
    @PostMapping(value = "updateTRoleMenuIdInfo")
    public ResponseResult updateTRoleMenuIdInfo(@RequestBody JSONObject jsonObject){
        Map<String,Object> map=jsonObject.getInnerMap();
        Integer roleId=null;
        if(!ConstentUtil.isEmpty(map)){

            roleId= Integer.parseInt(map.get("roleId").toString());
        }
        if(ConstentUtil.isEmpty(roleId)){
            logger.info("修改t_role_menu失败,roleId={}",roleId);
            return ResponseResult.fail("角色"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
//            //删除原有角色与菜单的对应关系
//            int delNum=tRoleMenuService.delete(roleId);
//            logger.info("删除t_role_menu成功，total={}",delNum);
//
//            //增加新的角色与菜单的绑定关系，如果菜单信息集合为空，则不需插入
//            if(ConstentUtil.isEmpty(map.get("menuIds"))){
//                logger.info("增加t_role_menu成功，map={}",map);
//                return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS,0);
//            }
//            int addNum=tRoleMenuService.insertRoleMenusInfo(map);

            //修改角色与菜单绑定关系
            int num=tRoleMenuService.updateMenuRole(map);
            if(num==-1 || num==-2){
                return ResponseResult.fail("请选择修改的角色菜单信息");
            }
            logger.info("修改t_role_menu成功，新增条数:{}",num);
            return ResponseResult.success(ReturnValueConstants.UPDATE_SUCCESS,num);
        } catch (Exception e) {
            logger.error("更新t_role_menu表异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }
}
